#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QString>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //窗体的名称
    this->setWindowTitle("串口调试助手V1.0");

    //连接信号与槽
    connect(&serial, &QSerialPort::readyRead, this, &MainWindow::receive_data);
    //connect(&serial, SIGNAL(readyRead()), this, SLOT(read_data()));   //两种方式

    //运行开始查找（遍历）可用串口
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->comboBox_num->addItem(info.portName());  //添加串口号到下拉菜单中
            serial.close();
        }
        qDebug() << "串口"<< info.portName() <<"搜索完成";
    }
    //波特率默认下拉菜单第1项
    ui->comboBox_baud->setCurrentIndex(1);
    //数据位默认下拉菜单第0项
    ui->comboBox_data->setCurrentIndex(0);
    //停止位默认下拉菜单第0项
    ui->comboBox_stop->setCurrentIndex(0);
    //校验位默认下拉菜单第0项
    ui->comboBox_veri->setCurrentIndex(0);
    //失能发送按钮
    ui->pushButton_tx->setDisabled(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_remove_rx_clicked() //清除接收框
{
    ui->text_rx->clear();
}

void MainWindow::on_pushButton_remove_tx_clicked() //清除发送框
{
    ui->text_tx->clear();
}

void MainWindow::on_pushButton_tx_clicked()         //发送数据
{
    QByteArray data = ui->text_tx->toPlainText().toLocal8Bit();
    //发送新行
    if(ui->checkBox->isChecked()) data += "\n";
    serial.write(data);
    data.clear();
}

void MainWindow::on_com_start_toggled(bool checked)  //打开串口
{
    if(checked)
    //if(ui->com_start->isChecked())
    {
        //设置串口号
        serial.setPortName(ui->comboBox_num->currentText());
        //设置波特率
        serial.setBaudRate(ui->comboBox_baud->currentText().toInt());
        //设置串口数据位
        switch(ui->comboBox_data->currentIndex())
        {
            case 0:
                serial.setDataBits(QSerialPort::Data8); break;
            case 1:
                serial.setDataBits(QSerialPort::Data7); break;
            case 2:
                serial.setDataBits(QSerialPort::Data6); break;
            case 3:
                serial.setDataBits(QSerialPort::Data5); break;
            default:    break;
        }
        //设置奇偶校验
        switch(ui->comboBox_veri->currentIndex())
        {
            case 0:
                serial.setParity(QSerialPort::NoParity); break;   //无校验位
            default:    break;
        }
        //设置停止位
        switch(ui->comboBox_stop->currentIndex())
        {
            case 0:
                serial.setStopBits(QSerialPort::OneStop); break;
            case 1:
                serial.setStopBits(QSerialPort::OneAndHalfStop); break;
            case 2:
                serial.setStopBits(QSerialPort::TwoStop); break;
            default:    break;
        }
        //流控设置
        serial.setFlowControl(QSerialPort::NoFlowControl);

        //打开串口（以读写方式）
        if(!serial.open(QIODevice::ReadWrite))
        {
            QMessageBox::critical(nullptr, "提示", "串口打开失败\r\n不存在或已被占用");
            ui->com_start->click();
            return;
        }
        qDebug() << "串口打开成功";
        ui->com_start->setText("关闭串口");
        ui->pushButton_tx->setEnabled(true);
        ui->comboBox_num->setEnabled(false);
        ui->comboBox_baud->setEnabled(false);
        ui->comboBox_veri->setEnabled(false);
        ui->comboBox_data->setEnabled(false);
        ui->comboBox_stop->setEnabled(false);
    }
    else
    {
        //关闭串口
        serial.close();
        ui->com_start->setText("打开串口");
        ui->pushButton_tx->setDisabled(true);
        ui->comboBox_num->setEnabled(true);
        ui->comboBox_baud->setEnabled(true);
        ui->comboBox_veri->setEnabled(true);
        ui->comboBox_data->setEnabled(true);
        ui->comboBox_stop->setEnabled(true);
    }
}

void MainWindow::receive_data() //接收串口数据
{
    //接收串口缓冲区数据
    QByteArray buffer= serial.readAll();
    //判断数据非空，处理数据
    if(!buffer.isEmpty())
        {
            QString str = ui->text_rx->toPlainText();   //获取显示窗口内容
            str+= QString(buffer);                          //拼接新数据
            ui->text_rx->clear();                       //清空显示窗口
            ui->text_rx->append(str);                   //重新显示
            str.clear();
        }
        buffer.clear();
}
